<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>图片lazy加载</title>
</head>

<body>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
  <script>
    // @description 准备为图片预加载使用的插件
    // 使用的图片容器css类名为lazy-load-wrap
    // 图片真实地址为data-lazy-src
    // 当lazy-load-wrap容器进入视口，则开始替换容器内所有需要延迟加载的图片路径，并更改容器的加载状态
    //第一种方法
    $.fn.compassLazyLoad = function () {
      var _HEIGHT = window.innerHeight,
        _lazyLoadWrap = $('.lazy-load-wrap');

      var methods = {
        setOffsetTop: function () {
          $.each(_lazyLoadWrap, function (i, n) {
            $(n).attr({
              'top': n.offsetTop - _HEIGHT,
              'status': 'wait'
            });
          })
        },
        isShow: function () {
          var _scrollTop = $(window).scrollTop;
          //利用image容器判断是否进入视口，而非image本身
          $.each(_lazyLoadWrap, function () {
            var _that = $(this);
            if (_that.attr('status') === 'done') {
              return;
            };
            if (_that.attr('top') <= _scrollTop) {
              _that.find('img[data-lazy-src]').each(function (i, n) {
                n.src = $(n).data('lazy-src');
              });
              _that.attr('status', 'done');
            };
          })
        },
        scroll: function () {
          $(window).on('scroll', function () {
            methods.isShow();
          });
        },
        init: function () {
          methods.setOffsetTop();
          methods.isShow();
          methods.scroll();
        }
      };
      methods.init();
    }
  </script>
</body>

</html>